$(function () {
    $('#role-dg').datagrid({
        striped: true,
        rownumbers: true,
        fitColumns: true,
        pagination: true,
        singleSelect: true,
        scrollbarSize: 0,
        width: "auto",
        url: 'role?method=findByPage',
        columns: [[
            {field: 'role', title: '角色', width: 15},
            {field: 'updatedTime', title: '更新时间', width: 15, align: 'center'},
        ]],
        onClickRow: function (index, row) {
            level3(row.id);
            $("#roleId").val(row.id);
        }
    });
    setTimeout(function () {
        level3();
    }, 100);


    $("#save").on("click", function () {
        $.ajax({
            type: "post",
            url: "roleSetting",
            data: {
                "method": "save",
                "roleId": $.trim($("#roleId").val()),
                "navIds": $.trim($("#checkedNodes").val())
            },
            dataType: "json",
            success: function (result) {
                let icon;
                if (result.status === 20000) {
                    icon = 1;
                } else {
                    icon = 2;
                }

                layer.msg(result.msg, {icon: icon});
            },
            error: function () {
                layer.msg("未知错误，请联系管理员或稍后重试", {icon: 2});
            }
        });
    });
});

function level3(roleId) {
    $.post("../menu", {method: "levelThree", roleId: roleId}, function (data) {
        $("#tree").tree({
            data: data,
            onCheck: function (node, checked) {
                let nodes = $('#tree').tree('getChecked', ['checked', 'indeterminate']);
                let checkedNodesId = [];
                $.each(nodes, function () {
                    if (this.id !== '0' && this.parentId !== '-1') {
                        checkedNodesId.push(this.id);
                    }
                });
                $("#checkedNodes").val(checkedNodesId);
            },
            onLoadSuccess: function () {
                let nodes = $('#tree').tree('getChecked', ['checked', 'indeterminate']);
                let checkedNodesId = [];
                $.each(nodes, function () {
                    if (this.id !== '0' && this.parentId !== '-1') {
                        checkedNodesId.push(this.id);
                    }
                });
                $("#checkedNodes").val(checkedNodesId);
            }
        });
    }, 'json');
}